import { getNewCarClueDetail } from '../../api/newCarClue/index'
import config from '../../config/index'
import { energyNature } from '../../enums/car/index'
import { getToken, getUserInfo } from '../../utils/storage'
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog'
import { checkClue } from '../../api/wxuser/index'
import { getWxAppConfig } from '../../api/wxAppConfig/index'

Page({
  data: {
    clueDetail: {} as ListNewCarClue,
    user: {} as WxUser,
    reduceCoin: 0,
    panelShow: false,
    lockShow: false,
    callShow: false,
    lock: false,
    outed: false,
    customerShow: false,
    wxConfig: {} as ListWxAppConfig,
    config: {} as Config
  },
  async initDetail(id: string) {
    const res = await getNewCarClueDetail(id)
    const configRes = await getWxAppConfig()
    if(res.statusCode === config.SUCCESS_CODE && configRes.statusCode === config.SUCCESS_CODE) {
      let user = getUserInfo()
      let detail = res.data as ListNewCarClue
      let enNature = energyNature.find(item => item.value === detail.energy) as nature
      detail.energy = enNature.label
      let reduceCoin: number
      if(user.userDiscount === 0) {
        reduceCoin = detail.useCoin
      } else {
        reduceCoin = Math.trunc(detail.useCoin * user.userDiscount / 100)
      }
      this.setData({
        clueDetail: detail,
        user,
        reduceCoin,
        wxConfig: configRes.data as ListWxAppConfig,
        config
      })
    } else {
      wx.showToast({title: '网络错误', icon: 'error'})
    }
  },
  clipStr() {
    wx.setClipboardData({
      data: this.data.wxConfig.customerWxStr as string,
      success: () => {
        wx.showToast({title: '复制成功', icon: 'none'})
      },
      fail: () => {
        wx.showToast({title: '复制失败', icon: 'none'})
      }
    })
  },
  previewPic() {
    let src = this.data.config.BaseUrl + '/' + this.data.wxConfig.customerWxPic
    wx.previewImage({
      current: src,
      urls: [src]
    })
  },
  contactCustomer() {
    this.setData({ customerShow: true });
  },
  onCustClose() {
    this.setData({ customerShow: false });
  },
  //判断是否登录
  checkLogin() {
    if(!getToken()) {
      wx.showToast({
        title: '未登录',
        icon: 'error',
        success: () => {
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/login/login'
            })
          }, 1000)
        }
      })
    }
  },
  lock() {
    //查看是否被锁定，已被锁定提示弹窗
    if(this.data.clueDetail.isLock) {
      wx.showToast({title: '此线索已被锁定', icon: 'error'})
      return
    }
    //查看是否购买
    checkClue(this.data.clueDetail.id as string, this.data.user.id).then((res) => {
      if(res.statusCode === config.SUCCESS_CODE) {
        //已购买直接开启锁定界面
        if(res.data) {
          this.setData({
            lockShow: true
          })
        } else {
          //未购买提示先获取电话号码消耗积分
          Dialog.alert({
            title: '未获取电话号码',
            message: '请先点击获取电话按钮获取权益'
          }).then(() => {})
        }
      } else {
        wx.showToast({title: '网络错误', icon: 'error'})
      }
    })
  },
  toIndex() {
    wx.reLaunch({
      url: '/pages/index/index'
    })
  },
  call() {
      //判断是否已经锁定
      if(this.data.clueDetail.isLock && this.data.clueDetail.lockWxUser !== this.data.user.id) {
        Dialog.alert({
          title: '已被他人锁定',
          message: `锁定时间为${this.data.clueDetail.startLockDate}至${this.data.clueDetail.endLockDate}`
        }).then(() => {})
        return
      }
      //判断是否已经购买过
      checkClue(this.data.clueDetail.id as string, this.data.user.id).then((res) => {
        if(res.statusCode === config.SUCCESS_CODE) {
          //已经购买过，直接打电话
          if(res.data) {
            this.showPhone()
          } else {
            //判断现在积分是否足够购买
            if(this.data.reduceCoin > this.data.user.coin) {
              //不够就开启充值
              this.setData({
                panelShow: true
              })
              return
            }
            this.setData({
              callShow: true
            })
          }
        } else {
          wx.showToast({title: '网络错误', icon: 'error'})
        }
      })
  },
  showPhone() {
    Dialog.confirm({
      title: '联系电话为',
      message: this.data.clueDetail.phone,
      confirmButtonText: '拨打电话'
    }).then(() => {
      wx.makePhoneCall({
        phoneNumber: this.data.clueDetail.phone
      })
    }).catch(() => {})
  },
  onCallClose(e: any) {
    this.setData({
      callShow: e.detail,
    })
  },
  onClose(e: any) {
    this.setData({
      panelShow: e.detail
    })
  },
  onLockClose(e: any) {
    this.setData({
      lockShow: e.detail
    })
  },
  reLaunch() {
    wx.reLaunch({
      url: `/pages/newCarClueDetail/newCarClueDetail?id=${this.data.clueDetail.id}`
    })
  },
  onLoad(e: any) {
    this.checkLogin()
    let id: string = e.id
    this.initDetail(id)
     //检查购买次数是否下架
    //  checkOuted(id).then((res) => {
    //   if(res.statusCode === config.SUCCESS_CODE) {
    //     if(res.data) {
    //       this.setData({
    //         outed: true
    //       })
    //     } else {
    //       this.setData({
    //         outed: this.data.clueDetail.outed
    //       })
    //     }
    //   }
    // })
    //调用锁定人是否为用户
    // if(this.data.clueDetail.lockWxUser === this.data.user.id) {
    //   this.setData({
    //     lock: false
    //   })
    //   return
    // }
    //检查锁定时间是否过期
    // checkExpire(id).then((res) => {
    //   if(res.statusCode === config.SUCCESS_CODE) {
    //     if(res.data) {
    //       this.initDetail(id)
    //       this.setData({
    //         lock: false
    //       })
    //     } else {
    //       this.setData({
    //         lock: this.data.clueDetail.isLock
    //       })
    //     }
    //   }
    // })
  },
  onShareAppMessage() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: this.data.clueDetail.brand + this.data.clueDetail.clueName
        })
      }, 1000)
    })
    return {
      title: this.data.clueDetail.brand + this.data.clueDetail.clueName,
      path: `/page/user?id=${this.data.clueDetail.id}`,
      promise 
    }
  }
})